package net.net23.sysdent;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileSelector extends JPanel {

	private static final long serialVersionUID = -200408792594832348L;

	private JButton browse;
	private JTextField path;
	private File currentFile;

	public FileSelector() {
		this("...", false);
	}

	public FileSelector(String browseText) {
		this(browseText, false);
	}

	public FileSelector(boolean editable) {
		this("...", editable);
	}

	public FileSelector(String browseText, boolean editable) {
		super(new BorderLayout());
		path = new JTextField();
		path.setEditable(editable);
		browse = new JButton(browseText);
		browse.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				browseFile();
			}
		});
		add(path, BorderLayout.CENTER);
		add(browse, BorderLayout.EAST);
	}

	protected void browseFile() {
		JFileChooser chooser = new JFileChooser(getCurrentFile());
		chooser.setMultiSelectionEnabled(false);
		int option = chooser.showOpenDialog(null);
		if (option == JFileChooser.APPROVE_OPTION) {
			setCurrentFile(chooser.getSelectedFile());
			path.setText(getCurrentFile().getAbsolutePath());
		}
	}

	public void setCurrentFile(File currentField) {
		this.currentFile = currentField;
	}

	public File getCurrentFile() {
		return currentFile;
	}

	public String getSelectedFile() {
		return path.getText();
	}

	public Component getPathField() {
		return path;
	}

}
